package ru.alexo.whiskey.events;

import java.io.IOException;
import java.io.OutputStream;

import ru.alexo.whiskey.Midi;
import ru.alexo.whiskey.util.TonesHelper;

/**
 * Event representing a single monophonic note.
 * 
 * @author Exaybachay
 */
public final class NoteEvent extends MusicEvent {

    private static final byte PAUSE_CODE = -1;

    private final byte code;

    /**
     * Creates a note event with specified velicity (volume), duration and code
     * 
     * @param velocity
     *            volume of the note
     * @param duration
     *            duration
     * @param code
     *            code of the note. Use {@link TonesHelper} for reference.
     */
    public NoteEvent(byte velocity, byte duration, byte code) {
	super(velocity, duration);
	this.code = code;
    }

    @Override
    public int serializeToStream(OutputStream dos, int offset) throws IOException {
	int durat = (4 * Midi.DEFAULT_TPQ / duration);

	if (code < 0) {
	    return durat;
	}

	sendLength(offset, dos);
	dos.write(NOTE_ON);
	dos.write(code);
	dos.write(DEFAULT_VOLUME);

	sendLength(durat, dos);
	dos.write(NOTE_OFF);
	dos.write(code);
	dos.write(DEFAULT_VOLUME);

	return 0;
    }

    /**
     * Creates a pause note event.
     * 
     * @param duration
     *            duration of the pause note.
     * @return A pause {@link NoteEvent}.
     */
    public static NoteEvent newPause(byte duration) {
	return new NoteEvent((byte) 100, duration, PAUSE_CODE);
    }

}
